package purchasePlan

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetPurchasePlanDetailByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetPurchasePlanDetailByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetPurchasePlanDetailByIdApiLogic {
	hostname, _ := os.Hostname()
	return &GetPurchasePlanDetailByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetPurchasePlanDetailByIdApiLogic) GetPurchasePlanDetailByIdApi(req *types.IdReq) (resp *types.PurchasePlanModel, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	planEntity, err := dao.PurchasePlanEntity.WithContext(l.ctx).Where(
		dao.PurchasePlanEntity.ID.Eq(req.Id),
		dao.PurchasePlanEntity.EnterpriseID.Eq(accountInfo.EnterpriseId),
	).First()
	if err != nil {
		return nil, errors.New("传递的主键错误")
	}
	var supplierIdList = make([]int64, 0)
	if planEntity.SupplierID > 0 {
		supplierIdList = append(supplierIdList, planEntity.SupplierID)
	}
	if planEntity.DefaultSupplierID > 0 {
		supplierIdList = append(supplierIdList, planEntity.DefaultSupplierID)
	}
	var supperNameMap = make(map[int64]string)
	if len(supplierIdList) > 0 {
		supplierEntities, err := dao.SupplierEntity.WithContext(l.ctx).Where(dao.SupplierEntity.ID.In(supplierIdList...)).Find()
		if err == nil && len(supplierEntities) > 0 {
			supperNameMap = k.ToMap(supplierEntities, func(item *model.SupplierEntity) (int64, string) {
				return item.ID, item.Name
			})
		}
	}
	// 查询采购员名字
	var purchaserName = ""
	if planEntity.PurchaserID > 0 {
		enterprisePersonEntity, err := dao.EnterprisePersonEntity.WithContext(l.ctx).Where(dao.EnterprisePersonEntity.ID.Eq(planEntity.PurchaserID)).First()
		if err == nil && enterprisePersonEntity != nil {
			purchaserName = enterprisePersonEntity.Name
		}
	}

	return &types.PurchasePlanModel{
		ID:                      planEntity.ID,                                                                                               // 主键id
		OrderNo:                 planEntity.OrderNo,                                                                                          // 操作流水号
		SupplierID:              planEntity.SupplierID,                                                                                       // 供应商,关联到supplier表主键id
		SupplierName:            supperNameMap[planEntity.SupplierID],                                                                        // 供应商名称
		DefaultSupplierID:       planEntity.DefaultSupplierID,                                                                                // 默认供应商,关联到supplier表主键id
		DefaultSupplierName:     supperNameMap[planEntity.DefaultSupplierID],                                                                 // 默认供应商名称
		PurchaserID:             planEntity.PurchaserID,                                                                                      // 采购员,关联到
		PurchaserName:           purchaserName,                                                                                               // 采购员
		SpuID:                   planEntity.SpuID,                                                                                            // 商品,关联到spu表主键id
		SnapshotSpuName:         planEntity.SnapshotSpuName,                                                                                  // 快照商品名称
		SnapshotProductImageURL: planEntity.SnapshotProductImageURL,                                                                          // 快照产品图片
		SnapshotSpuType:         planEntity.SnapshotSpuType,                                                                                  // 快照商品类型,0表示基础商品,1表示加工商品
		SnapshotUnit:            planEntity.SnapshotUnit,                                                                                     // 快照单位
		SnapshotCategory:        planEntity.SnapshotCategory,                                                                                 // 快照分类
		LossRate:                planEntity.LossRate.StringFixed(2),                                                                          // 快照损耗率
		ExpectationGoodsDate:    k.If(planEntity.ExpectationGoodsDate.IsZero(), 0, utils.TimestampToString(planEntity.ExpectationGoodsDate)), // 期望收货日期
		RequirementsCount:       planEntity.RequirementsCount.StringFixed(2),                                                                 // 需求数量
		SnapshotPrice:           planEntity.SnapshotPrice.StringFixed(2),                                                                     // 快照商品单价
		PurchaserPrice:          planEntity.PurchaserPrice.StringFixed(2),                                                                    // 采购单价
		PurchaserCount:          planEntity.PurchaserCount.StringFixed(2),                                                                    // 采购数量
		PurchaserAmount:         planEntity.PurchaserAmount.StringFixed(2),                                                                   // 采购金额
		Source:                  planEntity.Source,                                                                                           // 来源,0表示pc端手动点击订单,1表示定时任务,2表示手机端创建,3pc端手动创建
		Status:                  planEntity.Status,                                                                                           // 状态,0表示待采购,1表示完成采购,2表示已经生成采购单,3表示取消采购
		CancelReason:            planEntity.CancelReason,                                                                                     // 取消采购原因
		Remark:                  planEntity.Remark,                                                                                           // 备注
		CreatedAt:               utils.TimestampToString(planEntity.CreatedAt),                                                               // 创建时间
		UpdatedAt:               utils.TimestampToString(planEntity.UpdatedAt),                                                               // 更新时间
		Types:                   planEntity.Types,
	}, nil
}
